package org.thraex.pms.question.filter;

import lombok.extern.java.Log;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

/**
 * @Author 鬼王
 * @Date 2019/08/23 15:18
 */
@Log
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info(">>>>>>>>>>>>>>>>>> Execute #init(FilterConfig filterConfig)");
        log.info(">>>>>>>>>>>>>>>>>> init-param name " + filterConfig.getInitParameter("auth"));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info(">>>>>>>>>>>>>>>>>> Execute #doFilter(ServletRequest request, ServletResponse response, FilterChain chain)");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        log.info(">>>>>>>>>>>>>>>>>> Request servlet path: " + req.getServletPath());

        final String pn = "auth";
        if (Optional.ofNullable(req.getParameter(pn)).isPresent()) {
            chain.doFilter(request, response);
        } else {
            resp.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = resp.getWriter();
            writer.write("<h1 style='color: red;text-align: center;'>权限过滤</h1>");
            //writer.close();
        }
    }

    @Override
    public void destroy() {
        log.info(">>>>>>>>>>>>>>>>>> Execute #destroy()");
    }

}
